package com.easy.common.util;
//发送验证码邮件
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class EmailUtil {
    //邮箱地址
    private static final String FROM = "1803237603@qq.com";
    //邮箱授权码
    private static final String AUTH_CODE = "xtnaunxscezzfbif";
    private static final String HOST = "smtp.qq.com";
    private static final String PORT = "465";
    private static final Session session;
    //初始化邮件会话配置
    static {
        Properties props = new Properties();//属性配置,hashtable的子类
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(props, new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });
        //设置debug模式,可以查看详细的发送 log
        session.setDebug(true);
    }
    //发送邮件方法
    public static void sendEmail(String to, String text) {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));//发送到哪里去
            message.setSubject("优尚秒杀平台验证码");
            message.setContent("<h1 style='color:blue'>您的验证码为"+text+"</h1>", "text/html;charset=utf-8");
            Transport.send(message);
            System.out.println("发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送失败");
        }


    }
    //测试
    public static void main(String[] args) {
        EmailUtil.sendEmail("1803237603@qq.com", "ABCDEFG");

    }
}
